package edu.tongji.jiaowu.webapp.action;

import java.io.File;
import java.io.IOException;

import javax.servlet.ServletContext;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.multiaction.MultiActionController;

import com.tongji.quickCRUDQ.util.StringUtil;

import edu.tongji.jiaowu.service.PrintManager;

public class PrintController extends MultiActionController {
	private PrintManager printManager;
	
	public ModelAndView excel(HttpServletRequest request, HttpServletResponse response) throws IOException {
		String fileName=StringUtil.NVL(request.getParameter("fileName"),"export");
		response.setHeader("Content-Type","application/force-download");
		response.setHeader("Content-Type","application/vnd.ms-excel");
		response.setHeader("Content-Disposition","attachment;filename="+fileName+".xls");
		response.setCharacterEncoding("UTF-8");
		String exportContent=request.getParameter("exportContent");
		if (exportContent==null) {
			exportContent=(String) request.getAttribute("exportContent");
		}
		response.getWriter().print(exportContent); 
		return null;
	}
	

	public ModelAndView print(HttpServletRequest request, HttpServletResponse response) {
		try {
			String jasper = request.getParameter("jasper");
			String[] params = request.getParameterValues("params");
			ServletContext application = this.getServletContext();
			File reportFile = new File(application.getRealPath(jasper));
			byte[] bytes = printManager.reportStream(reportFile.getPath(), params);
			response.setContentType("application/pdf");
			response.setContentLength(bytes.length);
			ServletOutputStream ouputStream = response.getOutputStream();
			ouputStream.write(bytes, 0, bytes.length);
			ouputStream.flush();
			ouputStream.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	public PrintManager getPrintManager() {
		return printManager;
	}

	public void setPrintManager(PrintManager printManager) {
		this.printManager = printManager;
	}
}
